package com.majie.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.InputStream;

/**
 * 七牛云
 * 
 * @author Administrator
 *
 */
public class QiNiuYunService implements InitializingBean {
	@Autowired
	private UploadManager uploadManager;

	@Autowired
	private BucketManager bucketManager;

	@Autowired
	private Auth auth;

	@Autowired
	private QiNiuProperties properties;

	private StringMap putPolicy;

	/**
	 * 上传文件
	 * 
	 */
	public Response uploadFile(File file) throws QiniuException {
		Response response = this.uploadManager.put(file, null, getUploadToken());
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(file, null, getUploadToken());
			retry++;
		}
		return response;
	}

	/**
	 * 上文二进制流文件
	 * 
	 */
	public Response uploadFile(InputStream inputStream) throws QiniuException {
		Response response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
		int retry = 0;
		while (response.needRetry() && retry < 3) {
			response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
			retry++;
		}
		return response;
	}

	/**
	 * 根据key删除文件
	 * 
	 */
	public Response delete(String key) throws QiniuException {
		Response response = bucketManager.delete(properties.getBucket(), key);
		int retry = 0;
		while (response.needRetry() && retry++ < 3) {
			response = bucketManager.delete(properties.getBucket(), key);
		}
		return response;
	}

	/**
	 * 获取上传凭证
	 * 
	 */
	private String getUploadToken() {
		return this.auth.uploadToken(properties.getBucket(), null, properties.getExpires(), putPolicy);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.putPolicy = new StringMap();
		putPolicy.put("returnBody",
				"{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
	}
}
